package com.fancon.android.gardenjokesx.activity;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Rect;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ListView;

import com.fancon.android.emoji.keyboard.M05FloatPanel;
import com.fancon.android.emoji.widget.M05RichText;
import com.fancon.android.gardenjokesx.GardenJokesBaseActivity;
import com.fancon.android.gardenjokesx.R;
import com.fancon.android.gardenjokesx.adapter.ListCommentAdapter;
import com.fancon.android.gardenjokesx.entity.Comment;
import com.fancon.android.gardenjokesx.entity.Photo;
import com.fancon.android.gardenjokesx.entity.ReportErrors;
import com.fancon.android.gardenjokesx.entity.User;
import com.fancon.android.gardenjokesx.rpc.GardenJokesApiConnect;
import com.fancon.android.gardenjokesx.rpc.JsonPaser;
import com.fancon.android.gardenjokesx.utils.Constant;
import com.fancon.android.gardenjokesx.utils.GlobalDelegate;
import com.fancon.android.gardenjokesx.utils.StringUtil;
import com.fancon.android.gardenjokesx.utils.UserUtil;
import com.fancon.android.gardenjokesx.widget.IGlobalStorage;
import com.fancon.android.multithread.RequestUI;
import com.fancon.android.ui.widget.FanconProgressBar;

public class M05Activity extends GardenJokesBaseActivity {
	// for Emoji keyboard
	private M05FloatPanel panel = null;
	private Boolean isKeyBoardShow = false;
	private int index =1;
	private Boolean isFirst = true;
	private Boolean isEnd = false;
	private boolean loadingMore = false;
	private View footerView;
	// nut
	private Button mbtnView;
	private ListView commentList;
	public static M05RichText mEditComment;
	private ArrayList<Comment> mListComment;
	private ArrayList<Comment> mListUser;
	private String mPhotoID;
	private String mUserID;
	private String mUserIDPost;
	private String mButtonClick;
	private String mUserNameView;
	private int ScreenID;
	private boolean isActivate = false;
	public int indexList, topList;
	private ListCommentAdapter adapter = null;
	public static boolean m05IsChange = false;
	private ReportErrors report;
	private int numberEnter = 0;
	private String replyUserName = "";
	private Boolean isRefresh = false;
	private User user;
	private String commentTxt;
	private Comment cmnt;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.m05);
		
		// @binhbt-comment
		user = UserUtil.getInfoUserLogin(getApplicationContext());
		if (user != null) {
			mUserID = user.getUser_id();
		}
		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			mPhotoID = extras.getString(Constant.PHOTO_ID);
			mButtonClick = extras.getString(Constant.ID_BUTTON);
			mUserNameView = extras.getString("viewed_user_name");
			ScreenID = extras.getInt(Constant.SCREEN_ID);
			mUserIDPost = extras.getString("viewed_user_id");
			Log.d("M05 user pót", "ID: " + mUserIDPost);
			replyUserName = extras.getString("reply_user");
		}
		LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		footerView = layoutInflater.inflate(R.layout.listfooter, null, false);
		mListComment = new ArrayList<Comment>();
		mListUser = new ArrayList<Comment>();
		mbtnView = (Button) findViewById(R.id.m05_btnView);
		commentList = (ListView) findViewById(R.id.m05_listComment);
		commentList.setCacheColorHint(0);
		commentList.addFooterView(footerView);
		mEditComment = (M05RichText) findViewById(R.id.m05_editComment);
		//
		if (replyUserName != null) {
			mEditComment.append("@" + replyUserName + " ");
		}
		//
		Button emoji = (Button) findViewById(R.id.emoji_btn);
		emoji.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (!isKeyBoardShow) {
					showEmojiPanel();
				} else {
					hideEmojiPanel();
				}
			}
		});
		showListComment();
		commentList.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub
				indexList = commentList.getFirstVisiblePosition();
				View v = commentList.getChildAt(0);
				topList = (v == null) ? 0 : v.getTop();
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub
				// what is the bottom iten that is visible
				int lastInScreen = firstVisibleItem + visibleItemCount;

				// is the bottom item visible & not loading more already ? Load
				// more !
				if ((lastInScreen == totalItemCount) && !(loadingMore)
						&& (!isEnd) && (!isFirst)) {
					loadMore();
				}
			}

		});
		mbtnView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				try {
					Log.d("size list user", "" + mListUser.size());
					if (isActivate == false) {
						mbtnView.setBackgroundResource(R.drawable.m05_btn_activate);
						commentList.setAdapter(new ListCommentAdapter(
								M05Activity.this, mListUser, mUserID, ScreenID));
						isActivate = true;
					} else {
						commentList.setAdapter(adapter);
						adapter.notifyDataSetChanged();
						commentList.setSelectionFromTop(indexList, topList);
						mbtnView.setBackgroundResource(R.drawable.m05_btn);
						isActivate = false;
					}
				} catch (Exception e) {
					// TODO: handle exception
				}
			}
		});
		mEditComment.setOnKeyListener(new OnKeyListener() {
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if (event.getAction() == KeyEvent.ACTION_DOWN) {
					switch (keyCode) {
					case KeyEvent.KEYCODE_ENTER:
						GlobalDelegate.isRFM031 = true;
						numberEnter++;
//						if (numberEnter == 1) {
							Log.d("click enter", "enter");

							if (mEditComment.getRichText().length() == 0) {
								showDialog(getString(R.string.ERR5001,
										getString(R.string.Common_comment)));
								return false;
							}
							if (mEditComment.getRichText().length() > 500) {
								showDialog(getString(R.string.ERR5003,
										getString(R.string.Common_comment),
										Constant.MAX_LENGTH_COMMENT));
								return false;
							}
							try{
							ArrayList<Comment> tmp = new ArrayList<Comment>();
							cmnt = new Comment();
							cmnt.setComment_id("xxxxx");
							cmnt.setContent(URLEncoder
									.encode(StringUtil.removeFeedLine(mEditComment.getRichText()), "UTF-8").replace("+", "%20"));
							cmnt.setFirst_name(user.getFirst_name());
							cmnt.setLast_name(user.getLast_name());
							cmnt.setTime_post(0);
							cmnt.setUser_id(user.getUser_id());
							cmnt.setUrl_image(user.getUrl_image());
							cmnt.setUser_name(user.getUser_name());
							tmp.add(cmnt);
							tmp.addAll(mListComment);
							adapter = new ListCommentAdapter(M05Activity.this, tmp,
									mUserID, ScreenID);
							commentList.setAdapter(adapter);
							
							}catch (Exception e) {
								e.printStackTrace();
								// TODO: handle exception
							}
							commentTxt = mEditComment.getRichText();
							mEditComment.setText("");
							PostCommentRequest request = new PostCommentRequest(
									"M05", M05Activity.this);
							getGlobalState().getRequestQueue().addRequest(
									request);
							return true;
//						}
//						return true;
					default:
						break;
					}
				}
				return false;
			}
		});
		mEditComment.setOnTouchListener(new View.OnTouchListener() {

			@Override
			public boolean onTouch(View arg0, MotionEvent event) {
				// TODO Auto-generated method stub
				mEditComment.setInputType(InputType.TYPE_CLASS_TEXT);
				mEditComment.onTouchEvent(event);
				return true;
			}
		});
	}
	public void loadMore() {
		footerView.setVisibility(View.VISIBLE);
		index++;
		load();
	}
	private void load(){
		showListComment();
	}
	private void loadDataView() {
		if (adapter == null|| isFirst) {
			//adapter = new CommentAdapter(this, listComments);
			adapter = new ListCommentAdapter(M05Activity.this, mListComment,
					mUserID, ScreenID);
			commentList.setAdapter(adapter);
		} else {
			adapter.notifyDataSetChanged();
		}
	}

	private void showListComment() {
		try{
			ArrayList<Comment> tmp = getCommentOfPhoto(getIntent().getExtras().getString("listComment"));
			adapter = new ListCommentAdapter(M05Activity.this, tmp,
					mUserID, ScreenID);
			commentList.setAdapter(adapter);
		}catch (Exception e) {
			e.printStackTrace();
			// TODO: handle exception
		}
		ListCommentRequest request = new ListCommentRequest("M05",
				M05Activity.this);
		getGlobalState().getRequestQueue().addRequest(request);
	}
	public ArrayList<Comment> getCommentOfPhoto(String json) {
		ArrayList<Comment> lstComment = new ArrayList<Comment>();
		try {
			JSONObject jObject = new JSONObject(json);
				// comment
				JSONArray commentArr = jObject.getJSONArray(json);
				Comment comment = null;
				JSONObject comJson = null;
				for (int i = 0; i < commentArr.length(); i++) {
					comJson = commentArr.getJSONObject(i);
					comment = new Comment();
					if (comJson.opt("comment_id") != null) {
						comment.setComment_id(comJson.getString("comment_id"));
					}
					if (comJson.opt("content") != null) {
						comment.setContent(comJson.getString("content"));
					}
					if (comJson.opt("time_post") != null) {
						comment.setTime_post(comJson.getLong("time_post"));
					}
					if (comJson.opt("user_id") != null) {
						comment.setUser_id(comJson.getString("user_id"));
					}
					if (comJson.opt("user_name") != null) {
						comment.setUser_name(comJson.getString("user_name"));
					}
					if (comJson.opt("url_image") != null) {
						comment.setUrl_image(comJson.getString("url_image"));
					}
					if (comJson.opt("first_name") != null) {
						comment.setFirst_name(comJson.getString("first_name"));
					}
					if (comJson.opt("last_name") != null) {
						comment.setLast_name(comJson.getString("last_name"));
					}
					lstComment.add(comment);
				}
		} catch (JSONException e) {
			// Toast.makeText(mContext, mContext.getString(R.string.ERR0007),
			// Toast.LENGTH_LONG).show();
		}
		return lstComment;
	}
	private class ListCommentRequest extends RequestUI {

		private Activity context;
		private FanconProgressBar mProgressDialog;

		public ListCommentRequest(Object key, Activity activity) {
			super(key, activity);
			context = activity;
			if(isRefresh){
				mProgressDialog = FanconProgressBar.show(context,
						context.getString(R.string.common_loading));
			}
		}

		@Override
		public void execute() throws Exception {

			getListComment(context, mUserID, mPhotoID);
			mListUser.clear();
		}

		@Override
		public void executeUI(Exception ex) {
			if(mProgressDialog != null){
				mProgressDialog.dismiss();
			}
			footerView.setVisibility(View.GONE);
			loadDataView();
			isFirst = false;
			isRefresh = false;
			//@binhbt-comment
			//commentList.setSelectionFromTop(indexList, topList);
			if (mButtonClick != null) {
				if (mButtonClick.equals(Constant.BUTTON_VIEWALLCM)) {
					Log.d("click view all", "clickckckc");
					mEditComment.setInputType(InputType.TYPE_NULL);
				}
				if (mButtonClick.equals(Constant.BUTTON_REPLY)) {
					Log.d("user dc click2", mUserNameView);
					Log.d("click reply", "clickckckc");
					mEditComment.append("@" + mUserNameView + " ");
				}
			}
			getListCopyListComment();
		}
	}

	private class PostCommentRequest extends RequestUI {

		private Activity context;
		//private FanconProgressBar mProgressDialog;
		boolean ok = true;

		public PostCommentRequest(Object key, Activity activity) {
			super(key, activity);
			context = activity;
			//mProgressDialog = FanconProgressBar.show(context,
			//		context.getString(R.string.common_loading));
			//Update to global storage
			try{
				Photo currentPhoto = ((IGlobalStorage)(((Activity)(context)).getApplication())).getCurrentPhoto();
				((IGlobalStorage)(((Activity)(context)).getApplication())).getCurrentPhoto().setNumber_comment(currentPhoto.getNumber_comment()+1);
				((IGlobalStorage)(((Activity)(context)).getApplication())).getCurrentComment().add(cmnt);
				((IGlobalStorage)(((Activity)(context)).getApplication())).setChange(true);
				}catch (Exception e) {
					e.printStackTrace();
					// TODO: handle exception
				}
		}

		@Override
		public void execute() throws Exception {
			// TODO Auto-generated method stub
			ok = postComment(context, mUserID, mPhotoID,
					StringUtil.removeFeedLine(commentTxt));
			if (ok) {
				if (ScreenID == Constant.M03_1 || ScreenID == Constant.M03
						|| ScreenID == Constant.M04_L
						|| ScreenID == Constant.T02_L) {
					m05IsChange = true;
				}
				Log.d("post comment...", "thanh cong");
				getListComment(context, mUserID, mPhotoID);
				mListUser.clear();
			}
		}

		@Override
		public void executeUI(Exception ex) {
			//mProgressDialog.dismiss();
			try {
				if (!ok) {
					if ((report != null)
							&& report.getMessage().equals("ERR-BLOCKED")) {
						numberEnter = 0;
						AlertDialog alertDialog;
						AlertDialog.Builder builder = new AlertDialog.Builder(
								M05Activity.this);
						// builder.setTitle("Sorry you can't view this user");
						builder.setMessage(getString(R.string.common_block_message));
						builder.setPositiveButton("ok",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int arg1) {
										finish();

										dialog.dismiss();
									}
								});
						builder.setCancelable(false);
						alertDialog = builder.create();
						alertDialog.show();
					}
				} else {
					numberEnter = 0;
					adapter = new ListCommentAdapter(M05Activity.this,
							mListComment, mUserID, ScreenID);
					commentList.setAdapter(adapter);
					//mEditComment.setText("");
					//@binhbt
					commentList.setSelection(0);
					//commentList.setSelection(mListComment.size() - 1);
					isEnd = false;
					isFirst = true;
					index = 1;
					//
//					try{
//					Photo currentPhoto = ((IGlobalStorage)(((Activity)(context)).getApplication())).getCurrentPhoto();
//					((IGlobalStorage)(((Activity)(context)).getApplication())).getCurrentPhoto().setNumber_comment(currentPhoto.getNumber_comment()+1);
//					((IGlobalStorage)(((Activity)(context)).getApplication())).getCurrentComment().add(cmnt);
//					((IGlobalStorage)(((Activity)(context)).getApplication())).setChange(true);
//					}catch (Exception e) {
//						e.printStackTrace();
//						// TODO: handle exception
//					}
				}
				getListCopyListComment();
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
		}
	}

	/**
	 * request to server to post comment about photo
	 * 
	 * @param userID
	 * @param photoID
	 * @param content
	 * @return
	 */
	private boolean postComment(Activity context, String userID,
			String photoID, String content) {

		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
		nameValuePairs.add(new BasicNameValuePair("user_id", userID));
		nameValuePairs.add(new BasicNameValuePair("photo_id", photoID));
		try {
			nameValuePairs.add(new BasicNameValuePair("comment", URLEncoder
					.encode(content, "UTF-8").replace("+", "%20")));
			Log.d("M05", URLEncoder.encode(content, "UTF-8")
					.replace("+", "%20"));
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		GardenJokesApiConnect api = new GardenJokesApiConnect(context);
		String result = api.execPost(getApplicationContext(),
				GardenJokesApiConnect.GROUP_M, "postComment", nameValuePairs);
		Log.d("ket qua post comment", result);
		JsonPaser json = new JsonPaser();
		report = json.getReport(result);
		return report.isIs_success();
	}

	/**
	 * get list user comment of photo
	 * 
	 * @param userID
	 * @param photoID
	 */
	private void getListComment(Activity context, String userID, String photoID) {

		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
		nameValuePairs.add(new BasicNameValuePair("user_id", userID));
		nameValuePairs.add(new BasicNameValuePair("photo_id", photoID));
		nameValuePairs.add(new BasicNameValuePair("page_index", String
				.valueOf(index)));
		GardenJokesApiConnect api = new GardenJokesApiConnect(context);
		String result = api.execGet(getApplicationContext(),
				GardenJokesApiConnect.GROUP_M, "getCommentOfPhoto",
				nameValuePairs);
		Log.d("list comment", result);
		JsonPaser json = new JsonPaser();
		ArrayList<Comment> tmp = json.getCommentOfPhoto(result);
		if(tmp.size() >0){
			if(mListComment.size() ==0){
				mListComment = tmp;
			}else{
				mListComment.addAll(tmp);
			}
		}else{
			isEnd = true;
		}
		//mListComment = json.getCommentOfPhoto(result);
	}

	public void refresh() {
		GlobalDelegate.isRFM031 = true;
		isRefresh = true;
		isFirst = true;
		isEnd = false;
		index = 1;
		showListComment();
	}

	/*
	 * Lay danh sach thu gon cua user dang bai va user comment
	 */
	private void getListCopyListComment() {
		boolean ok = false;
		int i = 0;
		while (i < mListComment.size()) {
			String userID = mListComment.get(i).getUser_id();
			ok = true;
			for (int j = 0; j < mListUser.size(); j++) {
				String userIDCopy = mListUser.get(j).getUser_id();
				if (userID.equals(userIDCopy)) {
					ok = false;
					break;
				}
			}
			if (ok == true) {
				Comment cm = new Comment();
				cm.setUser_id(mListComment.get(i).getUser_id());
				cm.setUrl_image(mListComment.get(i).getUrl_image());
				cm.setUser_name(mListComment.get(i).getUser_name());
				try {
					// Fix for \n\n
					String firstName = StringUtil.removeFeedLine(URLDecoder
							.decode(mListComment.get(i).getFirst_name(),
									"UTF-8"));
					String lastName = StringUtil
							.removeFeedLine(URLDecoder
									.decode(mListComment.get(i).getLast_name(),
											"UTF-8"));
					cm.setContent(URLEncoder.encode(firstName, "UTF-8") + "%20"
							+ URLEncoder.encode(lastName, "UTF-8"));
				} catch (Exception e) {
					// TODO: handle exception
				}
				cm.setTime_post(-1);
				mListUser.add(cm);
			}
			i++;
		}
	}

	/*
	 * show dialog when have a error
	 */
	public void showDialog(String msg) {

		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(msg).setCancelable(true)
				.setNegativeButton("OK", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
					}
				});
		AlertDialog alert = builder.create();
		alert.show();
		numberEnter = 0;
	}

	@Override
	public void bindKeyBoard() {
		final FrameLayout rootContent = (FrameLayout) findViewById(android.R.id.content);
		rootContent.getViewTreeObserver().addOnGlobalLayoutListener(
				new OnGlobalLayoutListener() {
					Rect r = new Rect();

					@Override
					public void onGlobalLayout() {
						int currentBottom = r.bottom;
						rootContent.getWindowVisibleDisplayFrame(r);
						if (currentBottom == r.bottom) {
							// Log.d(TAG, "SAME Height");
							return; // nothing changed
						}
						// Log.d(TAG, "DIFFERENT Height");
						int heightDiff = rootContent.getRootView().getHeight()
								- r.bottom;
						if (heightDiff > 100) { // if more than 100 pixels, its
												// probably
												// a keyboard...
							Log.d("xxxx", "Keyboard visible");
							if (panel != null) {
								panel.hideEmojiKeyBoard();
							}
						}
					}
				});
	}

	public void showEmojiPanel() {
		View focusingView = getCurrentFocus();
		View anchor = findViewById(R.id.input_mss);
		if (focusingView instanceof M05RichText) {
			if (panel == null) {
				panel = new M05FloatPanel(anchor, (M05RichText) focusingView);
				panel.showPanelOnTop();
				isKeyBoardShow = true;
			} else {
				panel.showPanelOnTop();
				isKeyBoardShow = true;
			}

		}
	}

	public void hideEmojiPanel() {
		if (isKeyBoardShow) {
			panel.dismiss();
			isKeyBoardShow = false;
		}
	}

	@Override
	public void onBackPressed() {
		if (isKeyBoardShow
				|| (panel != null && panel.getKeyBoard() != null && !panel
						.getKeyBoard().isHide())) {
			if (panel.getKeyBoard() != null) {
				if (!panel.getKeyBoard().isHide()) {
					panel.getKeyBoard().dismiss();
				} else {
					panel.dismiss();
					isKeyBoardShow = false;
				}
			} else {
				panel.dismiss();
				isKeyBoardShow = false;
			}
		} else {
			super.onBackPressed();
		}
	}
}
